﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dtSearch.Engine;
using System.Data;
using Portal.Xml.Utility;


namespace DtSearchIndexService
{
    public class IndexServiceInfo
    {
        public string SiteId = "";
        public string AssetCode="";
        public string IndexPath = "";
        public string whatToIndex = "";
        public string excludeFilters = "";
        public bool ExecuteInThread = true;
    }


    public class IndexServiceInfoParser
    {
        public static DataSet CreateDataset()
        {
            DataSet ds = new DataSet();
            ds.Tables.Add("Info");

            ds.Tables["Info"].Columns.Add("SiteId");
            ds.Tables["Info"].Columns.Add("AssetCode");
            ds.Tables["Info"].Columns.Add("IndexPath");
            ds.Tables["Info"].Columns.Add("whatToIndex");
            ds.Tables["Info"].Columns.Add("excludeFilters");
            ds.Tables["Info"].Columns.Add("ExecuteInThread");

            return ds;
        }


        public static string GetXml(IndexServiceInfo OIndexServiceInfo)
        {
            DataSet ds = CreateDataset();
            ds.Tables["Info"].Rows.Add(new object[]{
                OIndexServiceInfo.SiteId,
                OIndexServiceInfo.AssetCode,
                OIndexServiceInfo.IndexPath,
                OIndexServiceInfo.whatToIndex,
                OIndexServiceInfo.excludeFilters,
                OIndexServiceInfo.ExecuteInThread
                
            });
            return ds.GetXml();
        }



        public static IndexServiceInfo ParseFromXml(string XmlData)
        {
            DataSet ds = XmlUtility.GetDataSetFromXml(XmlData);
            IndexServiceInfo OIndexServiceInfo = ParseFromDataRow(ds.Tables[0].Rows[0]);
            return OIndexServiceInfo;
        }


        public static IndexServiceInfo ParseFromDataRow(DataRow dr)
        {
            IndexServiceInfo OIndexServiceInfo = new IndexServiceInfo();
            OIndexServiceInfo.AssetCode = XmlUtility.GetString(dr, "AssetCode", true);
            OIndexServiceInfo.excludeFilters = XmlUtility.GetString(dr, "excludeFilters", true);
            OIndexServiceInfo.ExecuteInThread = XmlUtility.GetBoolean(dr, "ExecuteInThread", true);
            OIndexServiceInfo.IndexPath = XmlUtility.GetString(dr, "IndexPath", true);
            OIndexServiceInfo.whatToIndex = XmlUtility.GetString(dr, "whatToIndex", true);
            OIndexServiceInfo.SiteId = XmlUtility.GetString(dr, "SiteId", true);

            return OIndexServiceInfo;
        }
    }

    public class IndexServiceBll
    {
        static IndexJobSettings GetDialogSettings(IndexServiceInfo OIndexServiceInfo)
        {
            string IndexPath = OIndexServiceInfo.IndexPath;// @"E:\Projects\QNet.Portal\UniversityNet\UserDataStorage\DocumentArchives\sbv\Xml\Index";
            string whatToIndex = OIndexServiceInfo.whatToIndex+"<+>";// @"E:\Projects\QNet.Portal\UniversityNet\UserDataStorage\DocumentArchives\sbv\Xml\Archive<+>";
            string tempFolder = "";
            string maxMemToUseMB = "";
            string autoCommitIntervalEdit = "";
            string filenameFilters = "";
            string excludeFilters = OIndexServiceInfo.excludeFilters;
            IndexJobSettings settings = new IndexJobSettings();
            settings.IndexPath = IndexPath;
            settings.FoldersToIndex.Add(whatToIndex);
            settings.TempFileDir = tempFolder;
            int.TryParse(maxMemToUseMB, out settings.MaxMemToUseMB);
            int.TryParse(autoCommitIntervalEdit, out settings.AutoCommitIntervalMB);
            settings.IncludeFilters = Server.Tokenize(filenameFilters);
            settings.ExcludeFilters = Server.Tokenize(excludeFilters);
            return settings;
        }


        public static void Execute(
            IndexServiceInfo OIndexServiceInfo,
            string[] StoreFields,
            bool ExecuteInThread)
        {
            if (string.IsNullOrEmpty(OIndexServiceInfo.IndexPath))
            {
                //throw new Exception("IndexPath chưa thiết lập");
                return;
            }
            if (string.IsNullOrEmpty(OIndexServiceInfo.whatToIndex))
            {
                //throw new Exception("whatToIndex chưa thiết lập");
                return;
            }
            try
            {
                System.IO.Directory.CreateDirectory(OIndexServiceInfo.IndexPath);
            }
            catch { }
            try
            {
                System.IO.Directory.CreateDirectory(OIndexServiceInfo.whatToIndex);
            }
            catch { }
            bool ActiveCreate = false;
            string[] Files=System.IO.Directory.GetFiles(OIndexServiceInfo.IndexPath,"*.*");
            if (Files.Length == 0)
            {
                ActiveCreate = true;
            }
            IndexJob ij = new IndexJob();
           
            IndexJobSettings ijSettings = GetDialogSettings(OIndexServiceInfo);
            ijSettings.CopyTo(ij);
            ij.ActionAdd = true;
            ij.ActionRemoveDeleted = true;
            ij.ActionRemoveListed = true;
            ij.ActionCreate = ActiveCreate;
            ij.ExcludeFilters.Add("*.sche");
            
            if (StoreFields == null)
            {
                StoreFields = new string[] { "DocumentNo", "Subject", "Sapo", "Signer", "SignerTitle", "Scope", "ReleasedFrom", "DocType", "ReleasedDate","SearchReleasedDate", "PublicDate","PublicDate", "EffectedDate","SearchEffectedDate", "ExpiredDate","SearchExpiredDate", "Status", "Url", "Target", "Source", "Keyword", "PublishingStatus", "ImageUploadFile","WorkflowDefId" };
            }
            for (int iIndex = 0; iIndex < StoreFields.Length; iIndex++)
            {
                ij.StoredFields.Add(StoreFields[iIndex]);
            }
            ij.StoredFields.Add("Mfn"); 

            if (ij.IndexPath.Length < 2)
                return;

            Options opts = new Options();
            opts.BinaryFiles = BinaryFilesSettings.dtsoFilterBinaryUnicode;
            opts.Hyphens = HyphenSettings.dtsoHyphenAsSpace;
            opts.TextFlags = TextFlags.dtsoTfRecognizeDates | TextFlags.dtsoTfRecognizeDatesPresumeDMY;
            //opts.FieldFlags = FieldFlags.dtsoFfSkipFilenameField | FieldFlags.dtsoFfOfficeSkipHiddenContent;
            opts.UnicodeFilterMinTextSize = 6;
            opts.UnicodeFilterFlags = UnicodeFilterFlags.dtsoUfAutoWordBreakByCase |
                    UnicodeFilterFlags.dtsoUfAutoWordBreakByLength |
                    UnicodeFilterFlags.dtsoUfOverlapBlocks;
            opts.UnicodeFilterBlockSize = 4194304;
            opts.Save();
            if (ExecuteInThread)
            {
                ij.ExecuteInThread();
            }
            else
            {
                ij.Execute();
            }
        }
    }
}

